package com.huixuebao.common.intercepors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.common.enumeration.ResultCodeEnum;
import com.huixuebao.common.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTInterceptor implements HandlerInterceptor {

    private static final String accessToken = "access_token";  //token 前端传递的header
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(accessToken);
        ApiResult<String> apiResult = new ApiResult<>();
        try{
            JWTUtils.verify(token);//验证令牌
            return true;//放行请求
        }catch (SignatureVerificationException e){
            //无效签名(签名通知异常)
            e.printStackTrace();
            apiResult.setCode(ResultCodeEnum.ERROR_TOKENSIGNATURE.getCode());
            apiResult.setMessage(ResultCodeEnum.ERROR_TOKENSIGNATURE.getMessage());
        }catch (TokenExpiredException e){
            //token过期
            e.printStackTrace();
            apiResult.setCode(ResultCodeEnum.ERROR_TOKENTIMEERROR.getCode());
            apiResult.setMessage(ResultCodeEnum.ERROR_TOKENTIMEERROR.getMessage());
        }catch (AlgorithmMismatchException e){
            //token算法不一致
            e.printStackTrace();
            apiResult.setCode(ResultCodeEnum.ERROR_TOKENALGORERROR.getCode());
            apiResult.setMessage(ResultCodeEnum.ERROR_TOKENALGORERROR.getMessage());
        }catch (Exception e){
            //access_token无效
            e.printStackTrace();
            apiResult.setCode(ResultCodeEnum.ERROR_TOKEN.getCode());
            apiResult.setMessage(ResultCodeEnum.ERROR_TOKEN.getMessage());
        }
        //转换为json 返回给客户端  jackson
        String json = new ObjectMapper().writeValueAsString(apiResult);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
